package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApUnLikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnLikesBehaviorService;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Log4j2
public class ApUnLikesBehaviorServiceImpl extends ServiceImpl<ApUnLikesBehaviorMapper, ApUnlikesBehavior> implements ApUnLikesBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    /**
     * 保存不喜欢行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {
        //1校验参数
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser apUser = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = null;
        if (apUser == null) {
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(null, dto.getEquipmentId());
        }else {
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(apUser.getId(), dto.getEquipmentId());
        }
        //2.检查实体
        if (apBehaviorEntry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //3.保存或修改不喜欢行为
        ApUnlikesBehavior apUnlikesBehavior = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId()));
        if (apUnlikesBehavior==null){
            //保存不喜欢行为
            apUnlikesBehavior=new ApUnlikesBehavior();
            apUnlikesBehavior.setArticleId(dto.getArticleId());
            apUnlikesBehavior.setCreatedTime(new Date());
            apUnlikesBehavior.setEntryId(apBehaviorEntry.getId());
            apUnlikesBehavior.setType(Integer.valueOf(dto.getType()));
            save(apUnlikesBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            //修改不喜欢行为
            apUnlikesBehavior.setType(Integer.valueOf(dto.getType()));
            updateById(apUnlikesBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }
}
